using System;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.ResourceManagement.ResourceProviders;

/*
*Creater:Hyx
*Introduce:场景切换管理器，负责场景切换的底层逻辑
*Version:0.0.1
*ChangeLog:创建--2024.01.01
*/
namespace HyxFrame.Core
{
    public class ChangeSceneManager : MonoSingleton<ChangeSceneManager>
    {
        protected override void InitManager()
        {

        }
        /// <summary>
        /// 切换场景
        /// </summary>
        /// <param name="targetScene">目标场景名</param>
        /// <param name="action">切换完成回调</param>
        public void ChangeScene(SceneInfo targetScene, Action action = null)
        {
            LoadingScene(targetScene);
        }

        /// <summary>
        /// 通过loading切换场景
        /// </summary>
        /// <param name="targetScene">目标场景名</param>
        /// <param name="loadingScene">过渡场景名</param>
        /// <param name="action">切换完成回调</param>
        public void ChangeSceneByloading(SceneInfo targetScene, Action action = null)
        {
            // 通过中间过渡场景切换
            LoadScene(targetScene, "Loading", action);
        }

        void LoadScene(SceneInfo targetScene, string loadingScene = null, Action action = null)
        {
            AsyncOperationHandle<SceneInstance> handle = Addressables.LoadSceneAsync(loadingScene);

            handle.Completed += (AsyncOperationHandle<SceneInstance> obj) =>
            {
                if (obj.Status == AsyncOperationStatus.Succeeded)
                {
                    // 释放加载的场景
                    // Addressables.Release(obj);
                    LoadingScene(targetScene, action);
                }
                else
                {
                    Debug.LogError($"Load scene {loadingScene} failed!");
                }
            };
        }

        private void LoadingScene(SceneInfo targetScene, Action action = null)
        {
            UIManager.Instance.ClearPanelCache();

            QuickVarList data = new QuickVarList();
            data.Add(targetScene._sceneName);
            data.Add(targetScene._loadingBG);
            data.Add(action);
            UIManager.Instance.OpenPanel("LoadingPanel", data, UILAYER.LOADING, true);
        }


    }

    public struct SceneInfo
    {
        public string _sceneName; // 场景名
        public string _loadingBG;    // 背景名
    }
}